/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
import { message } from "ant-design-vue";
export function parseTime(time: any, cFormat?: string) {
    if (arguments.length === 0) {
        return null;
    }
    const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
    let date;
    if (typeof time === "object") {
        date = time;
    } else {
        if (typeof time === "string") {
            if (/^[0-9]+$/.test(time)) {
                // support "1548221490638"
                time = parseInt(time);
            } else {
                // support safari
                // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
                time = time.replace(new RegExp(/-/gm), "/");
            }
        }

        if (typeof time === "number" && time.toString().length === 10) {
            time = time * 1000;
        }
        date = new Date(time);
    }
    const formatObj: any = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay(),
    };
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key: any) => {
        const value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === "a") {
            return ["日", "一", "二", "三", "四", "五", "六"][value];
        }
        return value.toString().padStart(2, "0");
    });
    return time_str;
}
/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time: any) {
    if (time == 0) {
        return "none";
    } else if (time < 3600) {
        // less 1 hour
        return Math.ceil(time / 60) + "分钟前";
    } else if (time < 3600 * 24 * 2) {
        return Math.ceil(time / 3600) + "小时前";
    } else {
        return "none";
    }
}

// 时间换算
export function getDateRange(intervalDays: number) {
    let oneDayTime = 24 * 60 * 60 * 1000;
    let list = [];
    let lastDay;
    let dateNow = new Date();
    lastDay = new Date(dateNow.getTime() - intervalDays * oneDayTime);
    list.push(formateDate(lastDay));
    list.push(formateDate(dateNow));
    // if (bolPastTime == true) {
    // } else {
    //     lastDay = new Date(dateNow.getTime() + intervalDays * oneDayTime);
    //     list.push(formateDate(dateNow));
    //     list.push(formateDate(lastDay));
    // }
    return list;
}
export function formateDate(time: any) {
    let year = time.getFullYear();
    let month = time.getMonth() + 1;
    let day = time.getDate();

    if (month < 10) {
        month = "0" + month;
    }

    if (day < 10) {
        day = "0" + day;
    }

    return year + "-" + month + "-" + day + "";
}

export function downloadIframe(url: any) {
    const iframe = document.createElement("iframe") as any;
    iframe.style.display = "none"; // 防止影响页面
    iframe.style.height = 0; // 防止影响页面
    iframe.src = url;
    document.body.appendChild(iframe); // 这一行必须，iframe挂在到dom树上才会发请求
    setTimeout(() => {
        iframe.remove();
        message.success("下载成功");
    }, 1500);
}

/**
 * 根据开始时间结束时间获取一个智能的时长
 * @param time 时间
 * @returns {String} 时长
 * @example start getTimeDuration(0, 30000) , return "00:30"
 */
export function getTimeDuration(currs: number) {
    let time = currs * 1000;
    let unitSecond = 1000;
    let unitMinute = unitSecond * 60;
    let unitHour = unitMinute * 60;
    let unitDay = unitHour * 24;

    let hour: any = Math.floor((time % unitDay) / unitHour);
    let minute = Math.floor(((time % unitDay) % unitHour) / unitMinute);
    let second = Math.floor(
        (((time % unitDay) % unitHour) % unitMinute) / unitSecond
    );

    let ret = "";

    ret += (hour < 10 ? "0" + hour : hour) + ":";
    ret +=
        (minute < 10 ? "0" + minute : minute) +
        ":" +
        (second < 10 ? "0" + second : second);
    return ret;
}
/**
 * @description: 将时分秒转换成秒
 * @since: 2023-06-13 11:14:43
 * @param {any} time
 * @return {*}
 */
export function gettimeRever(time: any) {
    var len = time.split(":");
    if (len.length == 3) {
        var hour = time.split(":")[0];
        var min = time.split(":")[1];
        var sec = time.split(":")[2];
        return Number(hour * 3600) + Number(min * 60) + Number(sec);
    }
    if (len.length == 2) {
        var min = time.split(":")[0];
        var sec = time.split(":")[1];
        return Number(min * 60) + Number(sec);
    }
    if (len.length == 1) {
        var sec = time.split(":")[0];
        return Number(sec);
    }

    // var hour = time.split(':')[0];
    // var min = time.split(':')[1];
    // var sec = time.split(':')[2];
    // return  Number(hour*3600) + Number(min*60) + Number(sec);
}
/**
 * 根据文件url获取文件名
 * @param url 文件url
 */
export function getFileName(url: string) {
    const num = url.lastIndexOf("/") + 1;
    let fileName = url.substring(num);
    //把参数和文件名分割开
    fileName = decodeURI(fileName.split("?")[0]);
    return fileName;
}

/**
 * 根据文件url获取文件流
 * @param url 文件url
 */
export function downloadUrlFile(url: string) {
    // url = url.replace(/\\/g, "/");
    console.log(url);
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    //xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
    xhr.onload = () => {
        if (xhr.status === 200) {
            // 获取文件blob数据并保存
            exportRaw(getFileName(url), xhr.response);
            message.success("下载成功");
        }
    };
    xhr.send();
}

// 下载
export function exportRaw(name: string, data: any) {
    const urlObject = window.URL || window.webkitURL || window;
    const exportBlob = new Blob([data]);
    const save_link: any = document.createElementNS(
        "http://www.w3.org/1999/xhtml",
        "a"
    );
    save_link.href = urlObject.createObjectURL(exportBlob);
    save_link.download = name;
    save_link.click();
}

export const formatSize = (data: number) => {
    if (data < 1024) return data + 'B';
    
    const units = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    let u = -1;
    do {
        data /= 1024;
        ++u;    
    } while (data >= 1024);
    return data.toFixed(1) + ' ' + units[u];
}